package com.ysstech.system.controller;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.ysstech.common.annotation.YssLog;
import com.ysstech.common.annotation.YssPermissions;
import com.ysstech.common.enums.YssStatusEnum;
import com.ysstech.common.controller.BaseController;
import com.ysstech.common.entity.Menu;
import com.ysstech.common.entity.Region;
import com.ysstech.common.entity.Role;
import com.ysstech.common.entity.TreeNode;
import com.ysstech.common.entity.User;
import com.ysstech.common.exception.BusinessException;
import com.ysstech.common.util.DateUtil;
import com.ysstech.common.util.resultutil.RestResult;
import com.ysstech.common.util.resultutil.ResultGenerator;
import com.ysstech.common.entity.Dicvalue;
import com.ysstech.system.enums.SystemEnum;
import com.ysstech.system.feign.FeignActivitiService;
import com.ysstech.system.service.RoleService;
import com.ysstech.system.service.OrganizationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@Slf4j
@Api(tags = "角色管理api")
@RequestMapping(value = "/role")
public class RoleController extends BaseController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private FeignActivitiService feignActivitiService;

    @YssPermissions(value = {"system:role"})
    @ApiOperation(value = "跳转角色管理页面")
    @YssLog(module = "角色管理", remark = "跳转角色管理页面")
    @RequestMapping(value = "/page")
    public String page() throws Exception {
        return "system/role";
    }


    @ApiOperation(value = "获取用户角色信息")
    @RequestMapping(value = "/getRoles")
    @YssLog(module = "角色管理", remark = "获取用户角色信息")
    @ResponseBody
    public RestResult getRoles(String accessToken) {
        String json = (String) redisCacheManager.getCache(accessToken);
        User userinfo = JSONArray.parseObject(json, User.class);
        Map<String, Object> map = new HashMap<>();
        map.put("roles", userinfo.getRoles());
        List<Menu> setMenu = new ArrayList<>();
        List<Region> setRegion = new ArrayList<>();
        for (Role role : userinfo.getRoles()) {
            setMenu.addAll(role.getListMenu());
            setRegion.addAll(role.getListRegion());
        }
        map.put("listMenu", setMenu);
        map.put("listRegion", setRegion);
        return ResultGenerator.getSuccessResult("获取用户角色信息成功", map);
    }

    @YssPermissions(value = {"system:role"})
    @ApiOperation(value = "获取角色页面机构的状态的值")
    @YssLog(module = "角色管理", remark = "获取角色页面机构的状态的值")
    @PostMapping(value = "/init")
    @ResponseBody
    public RestResult init() throws Exception {
        String orgId = redisCacheManager.getLoginUserInfo().getOrgId();
        List<TreeNode> listOrganization = organizationService.queryOrganizationTree(orgId);
        List<Dicvalue> sysRoleType = dicValueService.getCacheDicValueList(SystemEnum.SYS_ROLE_TYPE.getCode());
        List<Dicvalue> sysStatus = dicValueService.getCacheDicValueList(SystemEnum.SYS_STATUS.getCode());
        Map<String, Object> map = new HashMap<>();
        map.put("listOrganization", listOrganization);
        map.put("sysRoleType", sysRoleType);
        map.put("sysRoleType2", sysRoleType);
        map.put("sysStatus", sysStatus);
        return ResultGenerator.getSuccessResult("获取页面初始化信息成功", map);
    }

    /**
     * 角色列表信息查询
     * 查询当前登录人所在机构和所有下级机构用户
     *
     * @return
     */
    @YssPermissions(value = {"system:role"})
    @ApiOperation(value = "获取机构下所有角色")
    @YssLog(module = "角色管理", remark = "获取机构下所有角色")
    @PostMapping(value = "/listInfo")
    @ResponseBody
    public RestResult listInfo(Role role, String page, String rows) throws Exception {
        // feignActivitiService.startProcessFlow("111111", "role", "1"); //启动流程
        return ResultGenerator.getSuccessResult("获取机构下所有角色信息成功",
                roleService.queryAllRoles(role, this.getPage(page, rows)));
    }


    /**
     * 新增角色的方法
     *
     * @param role
     * @return
     */
    @YssPermissions(value = {"system:role:add"})
    @ApiOperation(value = "新增角色信息")
    @YssLog(module = "角色管理", remark = "新增角色信息")
    @RequestMapping(value = "/addRole")
    @ResponseBody
    public RestResult addRole(Role role) throws Exception {
        role.setId(DateUtil.generateUUID());
        role.setAddTime(LocalDateTime.now());
        role.setStatus(YssStatusEnum.YSS_NORMAL.getCode());
        roleService.save(role);
        return ResultGenerator.getSuccessResult("新增角色信息成功！");
    }

    /**
     * 修改角色信息
     *
     * @return
     */
    @YssPermissions(value = {"system:role:edit"})
    @ApiOperation(value = "修改角色信息")
    @YssLog(module = "角色管理", remark = "修改角色信息")
    @RequestMapping(value = "/editRole")
    @ResponseBody
    public RestResult editRole(Role role) throws Exception {
        if (role == null || StringUtils.isBlank(role.getId())) {
            throw new BusinessException("获取角色信息失败，请稍后重试！");
        }
        role.setEditTime(LocalDateTime.now());
        roleService.updateById(role);
        return ResultGenerator.getSuccessResult("修改角色信息成功！");
    }

    /**
     * 删除角色信息
     *
     * @return
     */
    @YssPermissions(value = {"system:role:del"})
    @ApiOperation(value = "删除角色信息")
    @YssLog(module = "角色管理", remark = "删除角色信息")
    @RequestMapping(value = "/delRole")
    @ResponseBody
    public RestResult delRole(String ids) throws Exception {
        if (StringUtils.isBlank(ids)) {
            throw new BusinessException("获取删除角色信息失败，请稍后重试！");
        }
        List<String> list = JSONArray.parseArray(ids, String.class);
        roleService.batchDeleteRole(list);
        return ResultGenerator.getSuccessResult("删除角色信息成功！");
    }

    /**
     * 获取角色下的菜单权限
     *
     * @return
     */
    @YssPermissions(value = {"system:role:ent"})
    @ApiOperation(value = "获取角色下的菜单权限")
    @YssLog(module = "角色管理", remark = "获取角色下的菜单权限")
    @PostMapping(value = "/getFuncByRoleId")
    @ResponseBody
    public RestResult getFuncByRoleId(String roleId) throws Exception {
        List<TreeNode> list = roleService.quertMenuByRoleId(roleId);
        return ResultGenerator.getSuccessResult("获取角色下的菜单权限成功", list);
    }

    /**
     * 保存角色下的菜单权限
     *
     * @param roleId
     * @return
     */
    @YssPermissions(value = {"system:role:ent"})
    @ApiOperation(value = "保存用户角色信息")
    @YssLog(module = "角色管理", remark = "保存角色的菜单和按钮权限")
    @RequestMapping(value = "/saveAuthByRoleId")
    @ResponseBody
    public RestResult saveAuthByRoleId(String roleId, String arryMenu, String arryRegion) throws Exception {
        List<String> listMenu = null;
        List<String> listRegion = null;
        if (StringUtils.isNotBlank(arryMenu)) {
            listMenu = JSONArray.parseArray(arryMenu, String.class);
        }
        if (StringUtils.isNotBlank(arryRegion)) {
            listRegion = JSONArray.parseArray(arryRegion, String.class);
        }
        roleService.saveAuthByRoleId(roleId, listMenu, listRegion);
        return ResultGenerator.getSuccessResult("保存角色权限信息成功！角色下用户重新登录后生效！");
    }

    /**
     * 角色流程回调方法
     *
     * @param roleId
     * @param status
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updateRoleStatus")
    @ResponseBody
    public RestResult updateRoleStatus(String roleId, String status) throws Exception {
        Role role = new Role();
        role.setId(roleId);
        role.setStatus(Integer.valueOf(status));
        roleService.updateById(role);
        return ResultGenerator.getSuccessResult("修改角色状态成功！");
    }

}
